/**
 * 给fetch函数添加超时功能
 *
 * - 保持fetch的功能不变
 * - 没有侵入性
 * - 通用性
 */

/* const controller = new AbortController();

fetch("https://study.duyiedu.com/api/herolist", {
  signal: controller.signal
});

setTimeout(() => {
  controller.abort();
}, 10); */

const url = "https://study.duyiedu.com/api/herolist";

/**
 * 通用的高阶函数
 * @param {number} timeout 超时时间
 * @returns {(url: string, options: object) => Promise<any>} 一个request函数
 */
function createFetchWithTimeout(timeout = 1000) {
  return function (url, options) {
    return new Promise((resolve, reject) => {
      const signalController = new AbortController();
      fetch(url, {
        ...options,
        signal: signalController.signal
      }).then(resolve, reject);
      setTimeout(() => {
        reject(new Error("超时了"));
        // 取消请求
        signalController.abort();
      }, timeout);
    });
  };
}

// 测试
const request = createFetchWithTimeout(100);
request(url);
